package club.janna.hello.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Created by guopanbo on 17/11/27.
 */
public class Server {
    private int port;

    public Server(int port) {
        this.port = port;
    }

    public void start() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workGroup) //绑定两个线程组
                .channel(NioServerSocketChannel.class) //指定nio模式
                .childHandler(new ChannelInitializer<SocketChannel>() { //配置具体的数据处理方式
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        //System.out.println(1);
                        //ByteBuf buf = Unpooled.copiedBuffer("$_".getBytes());
                        //ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, buf));
                        //ch.pipeline().addLast(new StringDecoder());
                        //ch.pipeline().addLast(new Base64Decoder());
                        //ch.pipeline().addLast(new ReadTimeoutHandler(5 * 60));//5分钟内没有与服务器通讯则断开
                        ch.pipeline().addLast(new ServerHandle());
                    }
                })
                .option(ChannelOption.SO_BACKLOG, 128) //设置缓冲区
                .option(ChannelOption.SO_SNDBUF, 32 * 1024) //设置发送数据缓冲大小
                .option(ChannelOption.SO_RCVBUF, 32 * 1024) //设置接收数据缓冲大小
                .childOption(ChannelOption.SO_KEEPALIVE, true);//保持连接
        try {
            ChannelFuture future = bootstrap.bind(port).sync();
            System.out.printf("Server is already running, port %d, waiting connect ...\n", port);
            future.channel().closeFuture().sync();
            //System.out.println(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
